from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone

class AlarmRecord(models.Model):
    """报警记录模型"""
    SUBSCRIPTION_TYPES = (
        ('opcua', 'OPC UA'),
        ('mqtt', 'MQTT'),
    )

    name = models.CharField(
        max_length=100,
        verbose_name='数据名称',
    )
    subscription_type = models.CharField(
        max_length=10,
        choices=SUBSCRIPTION_TYPES,
        verbose_name='订阅类型'
    )
    opcua_subscription = models.ForeignKey(
        'subscriptions.OPCUASubscription',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name='OPC UA订阅'
    )
    mqtt_subscription = models.ForeignKey(
        'subscriptions.MQTTSubscription',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name='MQTT订阅'
    )
    mqtt_item = models.ForeignKey(
        'subscriptions.MQTTSubscriptionItem',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name='MQTT监控项'
    )
    value = models.FloatField(
        verbose_name='触发值'
    )
    message = models.TextField(
        verbose_name='报警消息'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='报警时间'
    )
    acknowledged = models.BooleanField(
        default=False,
        verbose_name='是否已确认'
    )
    acknowledged_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='acknowledged_alarms',
        verbose_name='确认人'
    )
    acknowledged_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='确认时间'
    )
    note = models.TextField(
        blank=True,
        verbose_name='备注'
    )

    class Meta:
        verbose_name = '报警记录'
        verbose_name_plural = '报警记录'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.get_subscription_type_display()} - {self.get_identifier()} - {self.created_at}"

    def get_data_source_name(self):
        """获取数据源名称"""
        subscription = self.opcua_subscription if self.subscription_type == 'opcua' else self.mqtt_subscription
        return subscription.data_source.name if subscription else "未知数据源"

    def get_identifier(self):
        """获取标识符（节点ID或主题）"""
        if self.subscription_type == 'opcua':
            return self.opcua_subscription.node_id if self.opcua_subscription else "未知节点"
        else:
            return self.mqtt_subscription.topic if self.mqtt_subscription else "未知主题" 